import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:orginone/components/LoadingWidget/LoadingWidget.dart';
import 'package:orginone/dart/base/model.dart';

import '../../../XStatefulWidget/XStatefulWidget.dart';

class MarkDownPreview extends XStatelessWidget<FileItemShare> {
  MarkDownPreview({super.key, super.data});

  @override
  Widget buildWidget(BuildContext context, FileItemShare data) {
    return FutureBuilder<String>(
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        if (snapshot.hasData) {
          return Container(
            margin: const EdgeInsets.only(top: 1),
            color: Colors.white,
            child: Markdown(
              imageBuilder: (uri, title, alt) =>
                  Image(image: AssetImage(uri.toString())),
              controller: ScrollController(),
              selectable: false,
              data: snapshot.data!,
            ),
          );
        }
        return LoadingWidget(
          isSuccess: snapshot.hasData,
          isLoading: !snapshot.hasData,
          child: Container(),
        );
      },
      future: loadMarkDownFile(data),
    );
  }

  Future<String>? loadMarkDownFile(FileItemShare data) async {
    if (null != data.shareLink && data.shareLink!.indexOf("assets") == 0) {
      return await rootBundle.loadString(data.shareLink!);
    }
    return Future<String>.value(null);
  }
}
